package com.ruoyi.file.service;

import com.alibaba.nacos.common.utils.IoUtils;
import com.aliyun.oss.OSS;
import com.ruoyi.file.config.AliYunOssConfig;
import com.ruoyi.file.utils.FileUploadUtils;
import java.io.InputStream;
import javax.annotation.Resource;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 阿里云 oss 文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
public class AliYunOssSysFileServiceImpl implements ISysFileService {

  @Resource
  private OSS ossClient;
  @Resource
  private AliYunOssConfig aliYunOssConfig;


  @Override
  public String uploadFile(MultipartFile file, boolean keepName) throws Exception {
    InputStream inputStream = null;
    try {
      String fileName = keepName ? file.getOriginalFilename() :
          FileUploadUtils.extractFilename(file);
      inputStream = file.getInputStream();
      System.out.println(ossClient);
      // 上传文件流。
      ossClient.putObject(aliYunOssConfig.getBucketName(), fileName, inputStream);
      return aliYunOssConfig.getFileAccessUrl() + fileName;
    } catch (Exception e) {
      throw new RuntimeException("OSS Failed to upload file", e);
    } finally {
      IoUtils.closeQuietly(inputStream);
    }
  }

}
